package com.easysoft.framework.action;

import com.easysoft.commons.utils.*;
import com.easysoft.framework.CustomUsernamePasswordToken;
import com.easysoft.framework.annotation.logs.SystemControllerLog;
import com.easysoft.framework.beans.Page;
import com.easysoft.framework.manager.model.SysManager;
import com.easysoft.framework.manager.model.SysManagerQuery;
import com.easysoft.framework.manager.model.SysManagerView;
import com.easysoft.framework.manager.service.SysManagerService;
import com.easysoft.framework.role.model.SysRole;
import com.easysoft.framework.role.model.SysRoleQuery;
import com.easysoft.framework.role.model.SysRoleView;
import com.easysoft.framework.role.model.UserRole;
import com.easysoft.framework.role.service.RoleService;
import com.easysoft.framework.role.service.UserRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;

@RestController
public class SystemManagerAction {
    public static final String BASE_VIEW = "/sysManager";
    private final static Logger logger = LoggerFactory.getLogger(SystemManagerAction.class);

    @Autowired
    @Qualifier("service.SysManagerService")
    private SysManagerService managerService;

    @Autowired
    @Qualifier("service.SysRoleService")
    private RoleService roleService;

    @Autowired
    @Qualifier("service.UserRoleService")
    private UserRoleService userRoleService;

    /**
     * 初次登录页面的跳转
     *
     * @param response
     * @param session
     * @return
     */
    @RequestMapping(value = "/", method = {RequestMethod.GET})
    public ModelAndView getSession(HttpServletResponse response, HttpSession session) {
        logger.info("-----------------------初次登录页面的跳转---------------");
        return new ModelAndView("/login");
    }

    /**
     * 管理员登录
     *
     * @param username 用户名
     * @param password 密码
     * @param password 验证码
     */
    @SystemControllerLog(description = "管理员登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(String username, String password, String captcha, HttpServletRequest request, HttpSession session) {
        logger.info("Call SystemManagerAction.login({},{},{})", username, password, captcha);
        if (!captcha.toLowerCase().equals(request.getSession().getAttribute(WebConstants.SESSION_SYS_CAPTCHA).toString().toLowerCase())) {
            return new ModelAndView(StringUtils.append("redirect:", request.getContextPath(), "/o/pwdLogin"));
        }
        if (StringUtils.isNullOrBlank(username) || StringUtils.isNullOrBlank(password)) {
            return new ModelAndView(StringUtils.append("redirect:", request.getContextPath(), "/o/pwdLogin"));
        }
        try {
            Subject subject = SecurityUtils.getSubject();
            CustomUsernamePasswordToken token = new CustomUsernamePasswordToken(username, password, LoginType.SHIRO_ADMIN_LOGIN);
            subject.login(token);
            SysManagerView sysManager = managerService.selectManagerByUserName(username);
            session.setAttribute(WebConstants.SESSION_USER_ID, sysManager.getId());
            session.setAttribute(WebConstants.SESSION_USER_NAME, username);
            session.setAttribute(WebConstants.SESSION_USER_ROLE, sysManager.getRoleCode());
            return new ModelAndView(StringUtils.append("redirect:", request.getContextPath(), "/welcome"));
        } catch (Exception e) {
            return new ModelAndView(StringUtils.append("redirect:", request.getContextPath(), "/o/pwdLogin"));
        }
    }

    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public ModelAndView welcome() {
        return new ModelAndView("/welcome");
    }

    /**
     * 系统管理员列表
     *
     * @param page  分页实体
     * @param query 查询条件
     * @return 管理员的实体列表
     */
    @RequestMapping(value = BASE_VIEW + "/listManager", method = RequestMethod.GET)
    public ModelAndView listManager(Page page, SysManagerQuery query, HttpSession session) {
        logger.info("Call SystemManagerAction.listManager({},{})", page.toString(), query.toString());
        query.setRoleCode((String) session.getAttribute(WebConstants.SESSION_USER_ROLE));
        List<SysManagerView> listManager = managerService.selectSysManagerListByPage(page, query);
        ModelAndView mv = new ModelAndView(BASE_VIEW + "/listManager");
        mv.addObject("page", page);
        mv.addObject("query", query);
        mv.addObject("listManager", listManager);
        return mv;
    }

    @RequestMapping(value = BASE_VIEW + "/editManager", method = RequestMethod.GET)
    public ModelAndView editManager(String action, @RequestParam(required = false) String id) {
        logger.info("Call SystemManagerAction.editManager({},{})", action, id);
        ModelAndView mv = new ModelAndView(BASE_VIEW + "/editManager");
        SysRoleQuery query = new SysRoleQuery();
        query.setPrefix("m:");
        List<SysRoleView> roles = roleService.selectSysRoleList(query);
        mv.addObject("roles", roles);
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("add")) {
            // 添加
            if (StringUtils.isNotNullAndBlank(id)) {
                return null;
            }
            return mv;
        }
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("update")) {
            // 修改
            if (StringUtils.isNullOrBlank(id)) {
                return null;
            }
            SysManagerView entity = managerService.selectSysManagerViewByPrimaryKey(id);
            if (entity == null) {
                return null;
            }
            mv.addObject("entity", entity);
            return mv;
        }
        return null;
    }

    @RequestMapping(value = BASE_VIEW + "/saveManager", method = RequestMethod.POST)
    public int saveManager(String action, SysManager manager, String roleId, HttpSession session) {
        logger.info("Call SystemManagerAction.saveManager({},{},{})", action, manager.toString(), roleId);
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("add")) {
            // 添加
            if (StringUtils.isNotNullAndBlank(manager.getId())) {
                return 0;
            }
            return addSysManager(manager, roleId, session);
        }
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("update")) {
            // 修改
            if (StringUtils.isNullOrBlank(manager.getId())) {
                return 0;
            }
            return updateSysManager(manager, roleId, session);
        }
        return 0;
    }

    /**
     * 添加管理员
     *
     * @param manager 管理员信息
     */
    @SystemControllerLog(description = "新增管理员信息")
    private int addSysManager(SysManager manager, String roleId, HttpSession session) {
        logger.info("Call SystemManagerAction.addSysManager({})", manager.toString());
        if (StringUtils.isNullOrBlank(manager.getUserName()) || StringUtils.isNullOrBlank(manager.getPassword()) || StringUtils.isNullOrBlank(manager.getMobile())) {
            // 用户名或密码或手机号为空
            return 0;
        }
        int count = managerService.countManagerByUserNameOrMobile(manager.getUserName(), manager.getMobile());
        if (count > 0) {
            // 用户名或手机号已存在
            return 0;
        }

        // 判断参数roleId是否正确
        SysRole role = roleService.selectSysRoleById(roleId);
        if (role == null) {
            // 参数roleId不正确
            return 0;
        }

        String salt = RandomUtils.getSpecialChart(4);
        manager.setId(UUIDUtils.getUUID());
        manager.setSalt(salt);
        manager.setPassword(DigestUtils.md5DigestAsHex((manager.getPassword() + salt).getBytes(Charset.forName("utf-8"))));
        manager.setSysType(3);
        manager.setOperator((String) session.getAttribute(WebConstants.SESSION_USER_ID));

        int flag = managerService.addSelective(manager);

        if (flag == 1) {
            // 添加用户角色信息
            UserRole userRole = new UserRole();
            userRole.setUserId(manager.getId());
            userRole.setRoleId(roleId);
            userRole.setOperator((String) session.getAttribute(WebConstants.SESSION_USER_ID));
            flag = userRoleService.addUserRole(userRole);
        }

        if (flag == 1) {
            return 1;
        } else {
            managerService.deleteByPrimaryKey(manager.getId());
            return 0;
        }
    }

    /**
     * 更新管理员信息
     *
     * @param manager 管理员信息
     */
    @SystemControllerLog(description = "更新管理员信息")
    private int updateSysManager(SysManager manager, String roleId, HttpSession session) {
        SysManagerView temp = managerService.selectSysManagerViewByPrimaryKey(manager.getId());
        if (temp == null) {
            return 0;
        }

        if (StringUtils.isNullOrBlank(manager.getPassword()) || StringUtils.isNullOrBlank(manager.getMobile())) {
            // 密码或手机号为空
            return 0;
        }

        manager.setUserName(temp.getUserName());

        // 密码被更改
        if (!manager.getPassword().equals(temp.getPassword())) {
            String salt = RandomUtils.getSpecialChart(4);
            manager.setSalt(salt);
            manager.setPassword(DigestUtils.md5DigestAsHex((manager.getPassword() + salt).getBytes(Charset.forName("utf-8"))));
        }

        // 角色被更改
        if (!temp.getRoleId().equals(roleId)) {
            userRoleService.deleteUserRoleByUserId(manager.getId());
            UserRole userRole = new UserRole();
            userRole.setUserId(manager.getId());
            userRole.setRoleId(roleId);
            userRole.setOperator((String) session.getAttribute(WebConstants.SESSION_USER_ID));
            userRoleService.addUserRole(userRole);
        }

        int flag = managerService.updateByPrimaryKeySelective(manager);

        if (flag == 1) {
            return 1;
        }

        return 0;
    }

    /**
     * 删除管理员
     *
     * @param id 管理员编号
     * @return
     */
    @SystemControllerLog(description = "删除管理员信息")
    @RequestMapping(value = BASE_VIEW + "/deleteManager", method = RequestMethod.POST)
    public String deleteSystemManager(String id) {
        logger.info("Call SystemManagerAction.deleteSystemManager({})", id);
        SysManager manager = managerService.selectByPrimaryKey(id);
        if (manager == null) {
            // 管理员不存在
            return "0";
        }

        int flag = managerService.deleteByPrimaryKey(id);
        if (flag == 1) {
            userRoleService.deleteUserRoleByUserId(id);
            // 删除成功
            return "1";
        }
        // 删除失败
        return "0";
    }
}
